<template>
  <!-- 备案表单内容区域 -->
  <div class="container">
    <!-- 引入公共头部组件 -->
    <HeaderMenu :title="title + '联系人'" leftText="返回" />
    <van-form
      @submit="onSubmit"
      style="height: 100%;overflow: auto;box-sizing: border-box;"
    >
      <div class="client" style="padding-bottom: 130px;">
        <van-field
          @click="CustomerClickChange"
          label="客户名称："
          placeholder="请选择客户"
          v-model="entity.CustomerName"
          :disabled="disabled"
          right-icon="edit"
          :readonly="isReadonly"
        >
        </van-field>
        <van-field
          label="姓名："
          placeholder="请输入姓名"
          v-model="entity.Name"
          :disabled="disabled"
        >
        </van-field>
        <van-field
          label="职位:"
          v-model="entity.Position"
          placeholder="请输入职位"
          :disabled="disabled"
        >
        </van-field>
        <van-field
          label="组织机构:"
          v-model="entity.Department"
          placeholder="请输入组织机构"
          :disabled="disabled"
        >
        </van-field>
        <div>
          <van-tag
            type="primary"
            v-for="(item, index) in WordList"
            :key="index"
            closeable
            class="tagClass"
            @close="closeTag(index)"
            >{{ item }}</van-tag
          >
          <van-field
            label="角色名称:"
            :disabled="disabled"
            @click="downRoleClick"
            v-model="entity.RoleName"
            placeholder="请输入角色名称(请使用【回车】分词)"
          >
          </van-field>
          <van-popup v-model="isShowRoleData" position="bottom">
            <van-picker
              show-toolbar
              :columns="columnsRoleData"
              @confirm="columnsRoleConfirm"
              @cancel="isShowRoleData = false"
              value-key="name"
            />
          </van-popup>
        </div>
        <!-- <van-popup v-model="showcProvince" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscProvince"
            @confirm="cProvinceConfirm"
            @cancel="showcProvince = false"
            value-key="name"
          />
        </van-popup> -->
        <van-field
          label="电话:"
          :disabled="disabled"
          v-model="entity.Tel_Code"
          placeholder="请输入电话"
        >
        </van-field>
        <van-field
          :disabled="disabled"
          label="电子邮箱:"
          v-model="entity.Email"
          placeholder="请输入电子邮箱"
        >
        </van-field>
        <van-field
          :disabled="disabled"
          label="省:"
          @click="showcProvinceClick"
          v-model="entity.cProvinceName"
          placeholder="请选择省份"
        >
        </van-field>
        <van-popup v-model="showcProvince" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscProvince"
            @confirm="cProvinceConfirm"
            @cancel="showcProvince = false"
            value-key="name"
          />
        </van-popup>
        <van-field
          :disabled="disabled"
          label="市:"
          @click="showcCity = true"
          v-model="entity.City"
          placeholder="请选择市"
        >
        </van-field>
        <van-popup v-model="showcCity" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscCity"
            @confirm="cCityConfirm"
            @cancel="showcCity = false"
            value-key="name"
          />
        </van-popup>
        <van-field
          :disabled="disabled"
          label="区:"
          @click="showcCounty = true"
          v-model="entity.County"
          placeholder="请选择区"
        >
        </van-field>
        <van-popup v-model="showcCounty" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscCounty"
            @confirm="cCountyConfirm"
            @cancel="showcCounty = false"
            value-key="name"
          />
        </van-popup>
        <van-field
          :disabled="disabled"
          label="详细地址:"
          @click="addressClick"
          v-model="entity.Address"
          placeholder="请输入详细地址"
          :readonly="isReadonly"
        >
        </van-field>
        <van-field
          :disabled="disabled"
          label="备注:"
          v-model="entity.Remark"
          placeholder="请输入备注"
        >
        </van-field>
        <van-popup v-model="showcCity" position="bottom">
          <van-picker
            show-toolbar
            :columns="columnscCity"
            @confirm="cCityConfirm"
            @cancel="showcCity = false"
            value-key="name"
          />
        </van-popup>
        <van-field label="上传名片" :disabled="disabled">
          <template #input>
            <!-- 考虑到除了新增，修改时也要用到这个页面，且只有单张照片，而且数据库里直接存的路径，在这里可以展示一下已经上传的图片，也可以做点击预览 -->
            <!-- <van-image
                :src="entity.reportPic"
                fit="contain"
                v-if="entity.reportPic !==''"
              /> -->
            <!-- 图片选择，上传前判断格式，删除前做数据处理  -->
            <van-uploader
              v-model="fileList"
              :after-read="afterRead"
              :before-delete="beforeDelete"
            />
          </template>
        </van-field>
      </div>
      <div style="margin: 16px" v-if="!disabled">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <!-- 编辑组件 -->
    <!-- <Edit :parentObj="this" ref="edit" /> -->
    <!-- 客户组件 -->
    <Myuser @customerChoice="Client" ref="myuser" v-show="ismyuser" />
    <!-- 地址组件 -->
    <Address @addressClickChange="AddressChangeChoice"  ref="address" v-show="isAddress" />
    
  </div>
</template>
<script>
import { Card, Toast } from "vant";
import {
  Search,
  NavBar,
  Pagination,
  Divider,
  Icon,
  Sticky,
  Uploader,
  DropdownMenu,
  DropdownItem,
  Popup
} from "vant";
// import Edit from "./Edit.vue";
// import Viewdetails from "./Viewdetails.vue";
import Address from "../../components/address.vue";
import Myuser from "../../components/OwnUser.vue";
import PaginationCom from "../../components/PaginationCom.vue";
// 引入公共头部组件
import HeaderMenu from "../../components/VolHeaderMenu.vue";
export default {
  components: {
    Address,
    Myuser,
    PaginationCom,
    // Viewdetails,
    "van-icon": Icon,
    "van-divider": Divider,
    "van-pagination": Pagination,
    "van-nav-bar": NavBar,
    "van-card": Card,
    "van-search": Search,
    "van-sticky": Sticky,
    "van-uploader": Uploader,
    "van-dropdown-menu": DropdownMenu,
    "van-dropdown-item": DropdownItem,
    "van-popup": Popup,
    // 公共头部组件
    HeaderMenu
    // Edit
  },
  data() {
    return {
      isReadonly:true,
      // 按钮是否禁用
      disabled: false,
      // 导航栏标题  0新增 1修改
      title: "",
      readonly: 0,
      // 上传后返回的图片路径
      thumbUrl: "",
      // 是否显示我的客户组件
      ismyuser: false,
      // 是否展示地址弹窗
      isAddress: false,
      obj: null,
      ListProvince: [],
      isShowRoleData: false,
      // 角色本来数据
      columnsRoleData: [
        "主管",
        "经理",
        "技术",
        "决策人",
        "老板",
        "采购负责人",
        "采购员",
        "技术主管",
        "总经理"
      ],
      // 角色名称标签数据
      WordList: [],
      // 上传附件列表数据
      fileList: [
        // { url: "https://img01.yzcdn.cn/vant/leaf.jpg" },
        // Uploader 根据文件后缀来判断是否为图片文件
        // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
        // { url: "https://cloud-image", isImage: true }
      ],
      // fileList: [
      //   { url: "https://img01.yzcdn.cn/vant/leaf.jpg" },
      //   // Uploader 根据文件后缀来判断是否为图片文件
      //   // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
      //   { url: "https://cloud-image", isImage: true }
      // ],
      columnscProvince: [], //省
      columnscCity: [], //市
      columnscCounty: [], //区
      listChildren: [],
      listcounty: [],
      showcCounty: false,
      // 是否展示省份弹窗
      showcProvince: false,
      // 显示市弹窗
      showcCity: false,
      entity: {
        CustomerName:"",
        reportPic: ""
      },
      // 1是编辑  0是新建
      urlType: 1
    };
  },
  async created() {
    this.urlType = this.$route.query.urlType;
    // 赋值增删改查类型
    this.readonly = this.$route.query.readonly;
    // 判断是编辑还是查看详情
    if (this.$route.query.readonly == 0) {
      // 新建
      this.title = "新建";
      // 显示提交按钮
      this.disabled = false;
      this.isReadonly=true
    } else if (this.$route.query.readonly == 1) {
      this.title = "编辑";
      // 编辑
      // 显示提交按钮
      this.disabled = false;
      this.isReadonly=true
    } else {
      // 查看
      this.title = "查看";
      this.readonly = true;
      this.disabled = true;
    }
    // 获取详情信息
    this.recordDetail(this.$route.query.Id);
    // 获取省份信息
    this.getProvinceListData();
     this.$set(this.entity, "ParentId");
  },
  methods: {
    // 上传名片
    //图片选择后回调，这里就是重点了，就是在选择照片后，将照片的信息封装到FormData对象中
    //注意我这里是单图上传，所以直接new了，如果是多图的话，应该要考虑添加和删除FormData中的元素
    afterRead(file) {
      //创建FormData对象。上传图片需要转换二进制，这里要用到FormData
      let forms = new FormData();
      //"file"表示给后台传的属性名字
      forms.append("file", file.file); //获取上传图片信息
      this.fileListData = file;
      file.status = "uploading";
      file.message = "上传中...";
      this.reportPicUpload(forms, file);
    },
    //图片删除前回调，删除时将公共变量forms中的文件信息一并删除
    beforeDelete(file) {
      forms = null;
      // this.fileListData=[]
      return true;
    },
    //图片上传，由提交按钮调用本方法实现手动上传
    reportPicUpload(params, file) {
      //如果文件列表为空，则不需要调用上传
      if (params == null || params.length == 0) {
        return;
      }
      this.http
        .post(
          "/CustomerManagement/Cust_CustomerLinkMan/UploadFileByForm",
          params
        )
        .then(res => {
          Toast.success("已上传");
          file.status = "done";
          if (res.thumbUrl) {
            this.$set(this.entity, "BusinessCardURL", res.thumbUrl);
            this.thumbUrl = res.thumbUrl;
          } else {
            Toast.fail(res.msg);
          }
        })
        .catch(err => {
          Toast.fail("图片上传失败");
          setTimeout(() => {
            file.status = "failed";
            file.message = "上传失败";
          }, 1000);
        });
    },

    // 获取联系人详情信息
    recordDetail(Id) {
      this.http
        .post("/CustomerManagement/Cust_CustomerLinkMan/GetTheData", { Id: Id })
        .then(res => {
          if (res.Success) {
            this.entity = res.Data;
          }
        })
        .catch(err => {
          Toast.fail(res.Msg);
        });
    },
    // 省份信息点击
    // 省份点击事件
    showcProvinceClick() {
      // this.getlist()
      // 显示省份弹窗
      this.showcProvince = true;
    },

    // 详细地址点击事件
    addressClick() {
      // 显示地址弹窗
      this.isAddress = true;
        // 调取子组件里的方法
        this.$refs.address.openForm();
        // 赋值给子组件id
        // this.$refs.address.queryParam[0].Keyword = this.entity.ParentId;
      // this.$nextTick(() => {
      
      // });
    },

    // 显示客户组件
    CustomerClickChange() {
      this.ismyuser = true;
      this.$nextTick(() => {
        this.$refs.myuser.openForm();
      });
    },

    // 地址组件传递过来的方法
    AddressChangeChoice(data) {
      // 将选中的数据赋值到form表单中
      this.entity.Address = data.Address;
      // 关闭地址弹窗
      this.isAddress = false;
    },

    //客户组件选择的本条客户的数据
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);
      this.$set(this.entity, "ParentId", a.Id);
    },

    // 客户组件传递过来的方法
    customerChoice(e) {},

    // 关闭角色名称
    closeTag(index) {
      console.log(index);
      this.WordList.splice(index, 1);
    },
    // 角色输入确定事件
    downRoleClick() {
      // 显示角色弹窗
      this.isShowRoleData = true;
    },
    // 角色数据点选
    columnsRoleConfirm(value) {
      if (!this.WordList) {
        this.WordList = [];
      }
      let a = this.WordList.includes(name);
      if (!a && value != "") {
        this.WordList.push(value);
      } else {
        Toast.fail("关键字不能重复或者为空");
      }
      // 关掉弹窗
      this.isShowRoleData = false;
      // this.entity.RoleName = "";
    },
    // 表单提交
    onSubmit() {
      if (this.readonly == 0) {
        if (!this.entity.CustomerName) {
          Toast("请先选择客户");
          return;
        }
        if (!this.entity.Name) {
          Toast("请输入姓名");
          return;
        }
        if (!this.entity.Position) {
          Toast("请输入职位");
          return;
        }
        if (!this.entity.Position) {
          Toast("请输入组织机构");
          return;
        }
        if (this.WordList.length == 0) {
          Toast("请先选择角色名称");
          return;
        }
        if (!this.entity.Tel_Code) {
          Toast("请输入电话");
          return;
        }
        if (!this.entity.Email) {
          Toast("请输入电子邮箱");
          return;
        }
        if (!this.entity.cProvinceName) {
          Toast("请选择省份");
          return;
        }
        if (!this.entity.City) {
          Toast("请选择市");
          return;
        }
        if (!this.entity.County) {
          Toast("请选择区");
          return;
        }
        if (!this.entity.Address) {
          Toast("请选择地址");
          return;
        }
        if (!this.entity.Address) {
          Toast("请选择详细地址");
          return;
        }

        // 新增
        this.http
          .post(
            "/CustomerManagement/Cust_CustomerLinkMan/SaveData",
            this.entity
          )
          .then(resJson => {
            this.loading = false;
            if (resJson.Success) {
              Toast.success("操作成功");
              this.$router.push({
                path: "/record"
                // query: {
                //   Id,
                //   cCusCode
                // }
              });
            } else {
              Toast(resJson.Msg);
            }
          });
      } else {
        // 编辑
        this.http
          .post(
            "/CustomerManagement/Cust_CustomerLinkMan/UpdateData",
            this.entity
          )
          .then(resJson => {
            if (resJson.Success) {
              Toast.success("修改成功!");
              //   this.$router.push({  后续有需求打开
              //   path: "/record"
              // });
            } else {
              Toast(resJson.Msg);
              //   this.$router.push({
              //   path: "/record"
              // });
            }
          });
      }
    },
    //获取省份信息
    getProvinceListData() {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=0", {})
        .then(resJson => {
          this.ListProvince = resJson.Data;
          this.columnscProvince = resJson.Data.map(item => {
            return item.Name;
          });
          if (!this.flag) {
            console.log(123);
            // this.getDataList();
          }
        });
    },
    // 获取市信息
    getCityListData(e) {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + e, {})
        .then(resJson => {
          this.listChildren = resJson.Data;
          this.columnscCity = resJson.Data.map(item => {
            return item.Name;
          });
          //市
          if (this.entity.cCity) {
            let arr2 = [this.entity.cCity].reduce((pre, cur) => {
              let idx = this.listChildren.findIndex(im => im.Id == cur);
              console.log(idx);
              pre.push(this.listChildren[idx]);
              return pre;
            }, []);
            if (arr2) {
              this.entity.City = arr2[0].Name;
              this.entity.cCity = arr2[0].Id;
            }
          }
        });
    },
    // 获取区信息
    getVillage(e) {
      this.http
        .post("/Base_BasicData/Base_District/GetDataListByPId?pId=" + e, {})
        .then(resJson => {
          this.listcounty = resJson.Data;
          this.columnscCounty = resJson.Data.map(item => {
            return item.Name;
          });

          if (this.entity.cCity) {
            let arr3 = [this.entity.cCounty].reduce((pre, cur) => {
              let idx = this.listcounty.findIndex(im => im.Id == cur);

              pre.push(this.listcounty[idx]);
              return pre;
            }, []);
            if (arr3) {
              this.entity.County = arr3[0].Name;
              this.entity.cCounty = arr3[0].Id;
            }
          }
        });
    },
    //区
    cCountyConfirm(value) {
      this.entity.County = value;
      let arr = [this.entity.County].reduce((pre, cur) => {
        let idx = this.listcounty.findIndex(im => im.Name == cur);
        console.log(idx);
        pre.push(this.listcounty[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.County = arr[0].Name;
      this.entity.cCounty = arr[0].Id;
      this.showcCounty = false;
    },
    //市
    cCityConfirm(value) {
      this.entity.City = value;
      let arr = [this.entity.City].reduce((pre, cur) => {
        let idx = this.listChildren.findIndex(im => im.Name == cur);
        console.log(idx);
        pre.push(this.listChildren[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.obj = arr;

      this.entity.City = arr[0].Name;
      this.entity.cCity = arr[0].Id;
      this.getVillage(this.entity.cCity);
      this.showcCity = false;
    },
    //省份确定事件
    cProvinceConfirm(value) {
      console.log(value);
      this.entity.cProvinceName = value;

      let arr = [this.entity.cProvinceName].reduce((pre, cur) => {
        let idx = this.ListProvince.findIndex(im => im.Name == cur);
        console.log(idx);
        pre.push(this.ListProvince[idx]);
        return pre;
      }, []);
      console.log(arr);
      this.entity.cProvinceName = arr[0].Name;
      this.entity.cProvince = arr[0].Id;
      this.getCityListData(this.entity.cProvince);
      this.showcProvince = false;
    }
  }
};
</script>
<style scoped>
.tagClass {
  color: #000;
  padding: 5px;
  background-color: #ccc;
  border-radius: 8px;
  margin-left: 15px;
  margin-bottom: 5px;
}
</style>
